package api

import (
	"github.com/gin-gonic/gin"
	"go-api/lib"
	"strconv"
	"time"
)

type timeApi struct {
}

func init() {
	c := &timeApi{}
	c.init(lib.R) //这里需要引入你的gin框架的实例
}

func (t timeApi) init(g *gin.Engine) {
	// 依次: 分页列表，单条，插入，修改，删除
	group := g.Group("/time")
	group.GET("/timestamp", t.ToTimestamp) //不设置限制条件的画默认查询所有
	group.GET("/now", t.Nowtime)
	group.GET("/datetime", t.ToDatetime)
	group.GET("/date", t.currentDate)
	group.GET("/time", t.currentTime)
}

// 时间转换为时间戳
func (t timeApi) ToTimestamp(c *gin.Context) {
	datetime := c.PostForm("datetime")
	if datetime == "" {
		lib.Resp.ErrorJson(c, 10001, "请输入正确时间!")
	}
	timestamp, _ := time.ParseInLocation(lib.Server.TimeFormat, datetime, time.Local)
	lib.Resp.SuccessJson(c, gin.H{"timestamp": timestamp.Unix()})
}

// 当前时间戳
func (t timeApi) Nowtime(c *gin.Context) {
	lib.Resp.SuccessJson(c, gin.H{"time": time.Now().Unix()})
}

// 当前日期时间
func (t timeApi) ToDatetime(c *gin.Context) {
	timestamp := c.PostForm("timestamp")
	if timestamp == "" {
		lib.Resp.ErrorJson(c, 10001, "请输入正确时间!")
	}
	formatTime, _ := strconv.ParseInt(timestamp, 10, 64)
	datetime := time.Unix(formatTime, 0).Format(lib.Server.TimeFormat)
	lib.Resp.SuccessJson(c, gin.H{"datetime": datetime})
}

// 当前日期
func (t timeApi) currentDate(c *gin.Context) {
	year, month, day := time.Now().Date()
	lib.Resp.SuccessJson(
		c,
		gin.H{"year": year, "month": month, "day": day},
	)
}

// 当前时间
func (t timeApi) currentTime(c *gin.Context) {
	now := time.Now()
	hour := now.Hour()
	minute := now.Minute()
	second := now.Second()
	lib.Resp.SuccessJson(
		c,
		gin.H{"hour": hour, "minute": minute, "second": second},
	)
}
